<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\utils;


use app\madmin\model\Configuration;
use app\madmin\model\PayMode;
use app\shop_admin\service\PicService;
use think\facade\Cache;

class Wechat
{
    /**
     * 获取微信参数
     * @param $baseIn
     * @param $method
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private static function getOptions()
    {
        $configuration = Configuration::where(['type' => "wxa"])->value("configuration");
        if (empty($configuration))
            throw new \Exception("未完善支付配置");
        $configuration = json_decode($configuration, true);

        return $configuration;
    }



    public static function preUploadImage($filePatch){

        $path = new \CURLFile($filePatch);
        $data=array('media'=>$path);

        //等比压缩图片
//        ImageHelper::compress($file, ['width' => 300, 'height' => 300, 'fixed' => true]);
        //提交图片素材
        $thumbMediaId = self::uploadImage();
    }


    /**
     * 上传图片
     * @param string $path
     * @return array|bool|mixed|void
     * @author
     */
    public static function uploadImage($file,$param=[])
    {

        $file_md5=md5($file).json_encode($param);


        $result=Cache::store('redis')->get($file_md5);

        if ($result){
            $data=json_decode($result,true);

            if (!empty($data['media_id'])){
                return $data;
            }

        }

        try{
            $parse_info = parse_url($file);
            if (!isset($parse_info['host']) && !file_exists($file)) {
                $picService = new PicService();
                list($code, $url) = $picService->getUrl();
                $file=$url.'/'.$file;

            }
            $parse_info = parse_url($file);
            if (isset($parse_info['host'])) {
                $type=getimgsuffix($file);
                $dir=public_path("storage/shop_admin");
                if(!is_dir($dir)){
                    mkdir($dir, 0777, true);
                    chmod($dir, 0777);
                }
                $local_file=$dir.time().".{$type}";
                //            if(!is_dir($dir)){
                //                mkdir($dir,777);
                //            }
                file_put_contents($local_file,file_get_contents($file));
                $file=$local_file;
            }
        }catch (\Exception $e){
            throw new \think\Exception($e->getMessage(),HTTP_NOTACCEPT);
        }

        if (!file_exists($file)) {
            throw new \think\Exception("文件上传失败",HTTP_NOTACCEPT);
        }

        if(!empty($param)){

            #$param=['width' => 300, 'height' => 300, 'fixed' => true];
            compress($file,$param);
        }

        $token = Wechat::getAccessToken();

        $url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $token . '&type=image';
        $result = self::httpPost($url, $file);
        Cache::store('redis')->set($file_md5, $result,60 * 60 * 24 * 2);
        $result=json_decode($result,true);
        unlink($file);
        return $result;
    }
    //上传素材图片的curl
    public static function httpPost($url, $data){
        $ch = curl_init();
        if (class_exists('\CURLFile')) {
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
            $data = array('media' => new \CURLFile($data));//>=5.5
        } else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            }
            $data = array('media' => '@' . realpath($data));//<=5.5
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, "TEST");
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    public static function getAccessToken(){

        $option=self::getOptions();
        $appid=$option['appid'];
        $secret=$option['appsecret'];
        $key="wx_access_token:".$appid;
        $token=Cache::store('redis')->get($key);

        if(empty($token)){
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
            $data=wx_request("get",$url);
            if (!empty($data['access_token'])){
                $token=$data['access_token'];
                Cache::store('redis')->set($key,$token,7200);
            }
        }
        return $token;
    }
    public static function getComponentAccessToken(){

    }
}